# Basic usage:
# perl form_generator 'dsn'
# then form config files will be generated in the tmp directory.
# This is the first draft.

{ 
    package My::Schema;
    use base qw/DBIx::Class::Schema::Loader/; 
    __PACKAGE__->loader_options();
}

use YAML;
use strict;

my $dsn    = $ARGV[0];
my $schema = My::Schema->connect( $dsn );
my %tables;
for my $table ( $schema->sources ) {
    my $source = $schema->source( $table );
    my %primary_columns = map {$_ => 1} $source->primary_columns;
    for my $col ( $source->columns ) {
        my $type;
        if( $primary_columns{$col} ){
            $type = 'Hidden';
        }
        else{
            $type = 'Text';
        }
        push @{$tables{$table}{elements}}, {
            type => $type,
            name => $col,
            label => $col,
        }
    }
    for my $rel( $source->relationships ) {
        my $info = $source->relationship_info($rel);
        my $rel_class = _strip_class( $info->{class} );
#        print Dump($info);
        push @{$tables{$table}{elements}}, {
            type => 'Select::DBIC',
            name => $rel,
            label => $rel,
            dbic_args => {
                resultset_name => $rel_class,
            }
        }
    }
    push @{$tables{$table}{elements}}, {
        type => 'Submit',
        name => 'foo',
    };
    push @{$tables{$table}{elements}}, {
        type => 'Hidden',
        name => $table . '_indicator',
        default => 1,
    };
    $tables{$table}{id} = $table;
    $tables{$table}{indicator} = $table . '_indicator';
    $tables{$table}{auto_id} = '%n';
    $tables{$table}{element_defaults} = {
        radiogroup => { auto_id => '%n_%c' }
    };
    $tables{$table}{auto_fieldset} = { legend => 'A fieldset' };
}

sub _strip_class {
    my $fullclass = shift;
    my @parts     = split /::/, $fullclass;
    my $class     = pop @parts;
    return $class;
}

for my $table( keys %tables ){
    open CONFIG, '>', "tmp/$table.yml" or die "Cannot open form config file: $!";
    print CONFIG Dump( $tables{$table} ); 
}


